// groupMessageListener.js
const { Api } = require('telegram');
const { NewMessage } = require('telegram/events');
const { getHandler } = require('./messageRouter');

class GroupMessageListener {
  constructor(client, channelId, accessHash) {
    this.client = client;
    this.channelId = channelId;
    this.accessHash = accessHash;
    this.started = false;
  }

  async start() {
    if (this.started) return;
    if (!this.client._sharedHandlerAdded) {
      this.client.addEventHandler(async (event) => {
        const peer = event.message.peerId;
        const channelId = peer?.channelId?.value;
        if (!channelId) return;

        const handler = getHandler(channelId);
        if (handler) await handler(event);
      }, new NewMessage({}));
      this.client._sharedHandlerAdded = true;
    }

    this.started = true;
    console.log(`✅  ${this.channelId} 注册路由监听成功`);
  }

  isListening() {
    return this.started;
  }
}

module.exports = GroupMessageListener;